package com.shanshi.activity;

import android.annotation.SuppressLint;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.shanshi.activity.addressSelector.activity.BaseActivity;
import com.shanshi.activity.addressSelector.adapters.ArrayWheelAdapter;
import com.shanshi.activity.addressSelector.widget.OnWheelChangedListener;
import com.shanshi.activity.addressSelector.widget.WheelView;
import com.shanshi.activity.request.UserInfo;
import com.shanshi.activity.response.AuditInfo;
import com.shanshi.activity.tool.CustomDialog;
import com.shanshi.activity.tool.OkHttpTool;


public class AuditInfoActivity extends BaseActivity implements  OnClickListener, OnWheelChangedListener,TextWatcher {

	private SharedPreferences sharedPreferences;
	private int userId;//用户id
	private TextView tv;
	private ImageView Iv;
	private Button sureBt;
	private ImageView choiceAdd;
	private EditText name;
	private TextView sex;
	private TextView birthday;
	private EditText familyNum;
	private EditText detailAddr;

	/****地址弹窗中的view******/
	private WheelView mViewProvince;
	private WheelView mViewCity;
	private WheelView mViewDistrict;
	private TextView tvCancel;
	private TextView tvSure;
	private TextView familyAddr;
	private RelativeLayout testPop;


	/***********时间选择器用到的变量*************/
	private int mYear;
	private int mMonth;
	private int mDay;
	final int DATE_DIALOG = 1;



	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.audit_info);

		init();
		initAddrPopWindow();

	}


	/*****初始化数据*****/
	@SuppressLint("ResourceAsColor")
	public void init(){
		sharedPreferences = AuditInfoActivity.this.getSharedPreferences("share", MODE_PRIVATE);
		userId = sharedPreferences.getInt("userId",7);
		Iv = (ImageView) findViewById(R.id.fanhui);
		Iv.setOnClickListener(this);
		sureBt = (Button) findViewById(R.id.sure);
		sureBt.setOnClickListener(this);
		tv = (TextView) findViewById(R.id.title);

		tv.setText("审核信息");
		familyAddr = (TextView) findViewById(R.id.familyAddr);
		familyAddr.setOnClickListener(this);
		tvCancel = (TextView) findViewById(R.id.addSelectorCancel);
		tvCancel.setOnClickListener(this);
		tvSure = (TextView) findViewById(R.id.addSelectorSure);
		tvSure.setOnClickListener(this);
		choiceAdd = (ImageView) findViewById(R.id.address);
		choiceAdd.setOnClickListener(this);
		name = (EditText) findViewById(R.id.name);
		sex = (TextView) findViewById(R.id.sex);
		sex.setOnClickListener(this);
		birthday = (TextView) findViewById(R.id.birthday);
		birthday.setOnClickListener(this);
		familyNum = (EditText) findViewById(R.id.familyNum);
		detailAddr = (EditText) findViewById(R.id.detailAddr);

		/************当内容没有填写完毕时不能点击确定按钮**************/
		name.addTextChangedListener(this);
		sex.addTextChangedListener(this);
		birthday.addTextChangedListener(this);
		familyNum.addTextChangedListener(this);
		familyAddr.addTextChangedListener(this);
		detailAddr.addTextChangedListener(this);
	}


	@Override
	public void onClick(View v) {

		switch(v.getId()){

			case R.id.fanhui:
				finish();
				break;

			case R.id.sure:
				UserInfo user = new UserInfo();
				user.setNickName(name.getText().toString());
				if(sex.getText().toString()=="男"){
					user.setSex(true);
				}else if(sex.getText().toString()=="女"){
					user.setSex(false);
				}
				user.setBirthday(birthday.getText().toString());
				user.setFamily(Integer.parseInt(familyNum.getText().toString()));
				user.setAddrProv(mCurrentProviceName);
				user.setAddrCity(mCurrentCityName);
				user.setAddrDis(mCurrentDistrictName);
				user.setAddrStree(detailAddr.getText().toString());
				OkHttpTool.doPost(OkHttpTool.BASE_URL + "users/" + userId + "/auditInfo", new Gson().toJson(user), new OkHttpTool.setOkhttpListener() {
					@Override
					public void onSuccess(String s) {
						AuditInfo content=new Gson().fromJson(s,AuditInfo.class);
						if(content.getCode()==10001){
							if(content.getData().getState()){
								handler.sendEmptyMessage(1);
							}else{
								handler.sendEmptyMessage(2);
							}

						}else{
							handler.sendEmptyMessage(3);

						}

					}

					@Override
					public void onFail() {
						handler.sendEmptyMessage(4);

					}
				});
				break;
			case R.id.birthday:
				showDialog(DATE_DIALOG);
				break;

			case R.id.sex:
				showSexDialog();
				break;

			case R.id.familyAddr:
//			 showAddrPopWindow();
				setEditTextCannotEdit();
				testPop = (RelativeLayout) findViewById(R.id.personalInfoPop);
				testPop.setVisibility(View.VISIBLE);
				break;

			case R.id.address:
//			 showAddrPopWindow();
				setEditTextCannotEdit();
				testPop = (RelativeLayout) findViewById(R.id.personalInfoPop);
				testPop.setVisibility(View.VISIBLE);
				break;

			case R.id.addSelectorCancel:
				setEditTextCanEdit();
				testPop.setVisibility(View.INVISIBLE);
				break;

			case R.id.addSelectorSure:
				setEditTextCanEdit();
				testPop.setVisibility(View.INVISIBLE);
				familyAddr.setText(mCurrentProviceName+mCurrentCityName+mCurrentDistrictName);
				break;
		}


	}


	/******设置输入框可以编辑******/
	public void setEditTextCanEdit(){
		name.setFocusable(true);
		name.setFocusableInTouchMode(true);
		sex.setFocusable(true);
		sex.setFocusableInTouchMode(true);
		birthday.setFocusable(true);
		birthday.setFocusableInTouchMode(true);
		familyNum.setFocusable(true);
		familyNum.setFocusableInTouchMode(true);
		detailAddr.setFocusable(true);
		detailAddr.setFocusableInTouchMode(true);
	}

	/******设置输入框不可以编辑******/
	public void setEditTextCannotEdit(){
		name.setFocusable(false);
		sex.setFocusable(false);
		birthday.setFocusable(false);
		familyNum.setFocusable(false);
		detailAddr.setFocusable(false);
	}



	/******初始化地址弹窗中的数据*********/
	public void initAddrPopWindow() {
		setUpViews();
		setUpListener();
		setUpData();
	}

	private void setUpViews() {
		mViewProvince = (WheelView) findViewById(R.id.id_province);
		mViewCity = (WheelView) findViewById(R.id.id_city);
		mViewDistrict = (WheelView) findViewById(R.id.id_district);
	}

	private void setUpListener() {
		// 添加change事件
		mViewProvince.addChangingListener(this);
		// 添加change事件
		mViewCity.addChangingListener(this);
		// 添加change事件
		mViewDistrict.addChangingListener(this);
	}

	private void setUpData() {
		initProvinceDatas();
		mViewProvince.setViewAdapter(new ArrayWheelAdapter<String>(AuditInfoActivity.this, mProvinceDatas));
		// 设置可见条目数量
		mViewProvince.setVisibleItems(7);
		mViewCity.setVisibleItems(7);
		mViewDistrict.setVisibleItems(7);
		updateCities();
		updateAreas();
	}

	@Override
	public void onChanged(WheelView wheel, int oldValue, int newValue) {
		// TODO Auto-generated method stub
		if (wheel == mViewProvince) {
			updateCities();
		} else if (wheel == mViewCity) {
			updateAreas();
		} else if (wheel == mViewDistrict) {
			mCurrentDistrictName = mDistrictDatasMap.get(mCurrentCityName)[newValue];
			mCurrentZipCode = mZipcodeDatasMap.get(mCurrentDistrictName);
		}
	}

	/**
	 * 根据当前的市，更新区WheelView的信息
	 */
	private void updateAreas() {
		int pCurrent = mViewCity.getCurrentItem();
		mCurrentCityName = mCitisDatasMap.get(mCurrentProviceName)[pCurrent];
		String[] areas = mDistrictDatasMap.get(mCurrentCityName);

		if (areas == null) {
			areas = new String[] { "" };
		}
		mViewDistrict.setViewAdapter(new ArrayWheelAdapter<String>(this, areas));
		mViewDistrict.setCurrentItem(0);
	}

	/**
	 * 根据当前的省，更新市WheelView的信息
	 */
	private void updateCities() {
		int pCurrent = mViewProvince.getCurrentItem();
		mCurrentProviceName = mProvinceDatas[pCurrent];
		String[] cities = mCitisDatasMap.get(mCurrentProviceName);
		if (cities == null) {
			cities = new String[] { "" };
		}
		mViewCity.setViewAdapter(new ArrayWheelAdapter<String>(this, cities));
		mViewCity.setCurrentItem(0);
		updateAreas();
	}



	/************创建时间弹窗***************/
	@Override
	protected Dialog onCreateDialog(int id) {
		switch (id) {
			case DATE_DIALOG:
				return new DatePickerDialog(this, mdateListener, mYear, mMonth, mDay);
		}
		return null;
	}

	/**
	 * 设置日期 利用StringBuffer追加
	 */
	public void display() {
		String month = (mMonth+1)+"";
		String day = mDay+"";
		if(mMonth+1<10){
			month = "0"+month;
		}
		if(mDay<10){
			day = "0"+day;
		}
		birthday.setText(new StringBuffer().append(mYear).append("-").append(month).append("-").append(day));
	}

	private DatePickerDialog.OnDateSetListener mdateListener = new DatePickerDialog.OnDateSetListener() {

		@Override
		public void onDateSet(DatePicker view, int year, int monthOfYear,
							  int dayOfMonth) {
			mYear = year;
			mMonth = monthOfYear;
			mDay = dayOfMonth;
			display();
		}
	};

	/***********展示性别选择弹窗************/
	public void showSexDialog(){
		CustomDialog.Builder builder = new CustomDialog.Builder(this);
		builder.setTitle("请选择性别：");
		builder.setPositiveButton("女", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {
				dialog.dismiss();
				sex.setText("女");
//	                //设置你的操作事项
			}
		});

		builder.setNegativeButton("男",
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
						dialog.dismiss();
						sex.setText("男");
					}
				});

		CustomDialog customDialog = builder.create(R.layout.complete_personnal_info_sexpopwindow,R.id.sex_title,R.id.sex_man,R.id.sex_woman,0,0);
		customDialog.show();

		//设置弹窗之外的部分不能点击
		customDialog.setCanceledOnTouchOutside(false);
	}


	@Override
	public void beforeTextChanged(CharSequence s, int start, int count, int after) {

	}

	@Override
	public void onTextChanged(CharSequence s, int start, int before, int count) {

	}

	@Override
	public void afterTextChanged(Editable s) {
		if(TextUtils.isEmpty(name.getText().toString())||TextUtils.isEmpty(sex.getText().toString())||TextUtils.isEmpty(birthday.getText().toString())||
				TextUtils.isEmpty(familyNum.getText().toString())||TextUtils.isEmpty(familyAddr.getText().toString())
				||TextUtils.isEmpty(detailAddr.getText().toString())){
			sureBt.setEnabled(false);
			sureBt.setBackgroundResource(R.drawable.button_style3);
		}else{
			sureBt.setEnabled(true);
			sureBt.setBackgroundResource(R.drawable.button_style);
		}
	}

	Handler handler=new Handler() {
		public void handleMessage(android.os.Message msg) {
			switch (msg.what) {
				case 1:
					Intent intent = new Intent(AuditInfoActivity.this,SpreadMessage.class);
					startActivity(intent);
					break;
				case 2:
					Toast.makeText(AuditInfoActivity.this, "对不起，您答对的项目少于4项，审核失败" ,Toast.LENGTH_LONG).show();
					break;
				case 3:
					Toast.makeText(AuditInfoActivity.this, "请求参数错误" ,Toast.LENGTH_LONG).show();
					break;
				case 4:
					Toast.makeText(AuditInfoActivity.this, "请求url错误" ,Toast.LENGTH_LONG).show();
					break;
			}
		}
	};

}
